package blueprint4j.license;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Properties;

import blueprint4j.utils.Base64;

public class LicenseProperties implements License {
	final private static String SIGNATURE_NAME="signature";
	final private static SimpleDateFormat DATE_FORMAT=new SimpleDateFormat("yyyy-MM-dd");
	
	private Properties properties;
	
	public LicenseProperties(Properties properties){
		this.properties=properties;
	}
	
	private byte[] getPropertiesBytes(Properties codeProperties){
		String[] keys=codeProperties.keySet().toArray(new String[0]);
		Arrays.sort(keys);
		
		StringBuffer values=new StringBuffer();
		for (String key:keys){
			if (!SIGNATURE_NAME.equals(key)){
				values.append(codeProperties.getProperty(key));
			}
		}
		return values.toString().getBytes();
	}
	
	public boolean validate(Properties codeProperties){
		// get the signature bytes
//		ByteArrayOutputStream out=new ByteArrayOutputStream();
//		String code=codeProperties.getProperty(SIGNATURE_NAME);
//		while (code.length()>1){
//			char c=code.charAt(0);
//			char d=code.charAt(1);
//			if (((c>='0' && c<='9') || (c>='a' && c<='f')) && ((d>='0' && d<='9') || (d>='a' && d<='f'))){
//				out.write(((byte)Integer.parseInt(code.substring(0,2),16)));
//				code=code.substring(2);
//			}else{
//				code=code.substring(1);
//			}
//		}
//				
//		byte[] buffer=out.toByteArray();
		byte[] buffer=Base64.decode(codeProperties.getProperty(SIGNATURE_NAME));

		ElGamal.PublicKey pk=new ElGamal.PublicKey(properties);
		ElGamal eg=new ElGamal();
		eg.setPublicKey(pk);
		return eg.verify(buffer, getPropertiesBytes(codeProperties));
	}
	
	public Properties generateCode(Properties codeProperties){
		ElGamal.PublicKey publicKey=new ElGamal.PublicKey(properties);
		ElGamal.PrivateKey privateKey=new ElGamal.PrivateKey(properties);
		ElGamal eg=new ElGamal();
		eg.setPrivateKey(privateKey);
		eg.setPublicKey(publicKey);
		
		Properties result=new Properties();
		result.putAll(codeProperties);

		byte[] encrypted=eg.sign(getPropertiesBytes(codeProperties));
		result.setProperty(SIGNATURE_NAME, new String(Base64.encode(encrypted)));
//		StringBuffer sb=new StringBuffer();
//		for (int t=0;t<encrypted.length;t++){
//			String hex=Integer.toString(((int)(encrypted[t]))&255,16);
//			if (hex.length()<2){
//				sb.append("0");
//			}
//			sb.append(hex);
//		}
//		result.setProperty(SIGNATURE_NAME, sb.toString());
		
		return result;
	}
}
